package main

import (
	"io"
	"net/http"
	"net/url"
	"os"
	"path"
	"strings"
    "path/filepath"

	"github.com/gin-gonic/gin"
)

func IndexController(c *gin.Context) {
}

func SimpleController(c *gin.Context) {
	name := strings.ToLower(c.Param("name"))
	simple := Global.Simples[Global.CurrentIndex]
	target_simple := path.Join(simple.SimplesCacheDir(), name)

	if !Global.Offline {
		// 非离线状态
		index_url, err := url.JoinPath(simple.URL, name)
		if err != nil {
			panic(err)
		}

		response, err := http.Get(index_url)

		if err != nil {
			panic(err)
		}
		defer response.Body.Close()

		if response.StatusCode == http.StatusOK {
			content, err := io.ReadAll(response.Body)
			if err != nil {
				panic(err)
			}

			err = os.WriteFile(target_simple, content, 0666)
			if err != nil {
				panic(err)
			}
		}
	}

	_, err := os.Stat(target_simple)
	if err != nil {
		if os.IsNotExist(err) {
			c.HTML(http.StatusNotFound, "not_found.html", gin.H{})
			return
		}
		c.HTML(http.StatusInternalServerError, "internal_server_error.html", gin.H{})
		return
	}

	conent, err := os.ReadFile(target_simple)

	if err != nil {
		panic(err)
	}

	c.Writer.Write(conent)
}

func PackageController(c *gin.Context) {
	simple := Global.Simples[Global.CurrentIndex]
	target_file := path.Join(simple.PackagesCacheDir(), c.Request.URL.Path)

	if !Global.Offline {
		// 非离线状态
		target_url := simple.JoinWithBase(c.Request.URL.Path)

		target_dir := filepath.Dir(target_file)

		mode := os.FileMode(0755)
		err := os.MkdirAll(target_dir, mode)
		if err != nil {
			panic(err)
		}
		DownloadFile(target_url, target_file)
	}
	f, err := os.Open(target_file)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	io.Copy(c.Writer, f)
	return
}
